<script lang="ts" setup>
import dayjs from 'dayjs'
import Calendar from '../student/components/Calendar.vue'
import type { CalendarEvent } from '../student/components/Calendar.vue'
import { ClassScheduleApi } from '@/apis'
import { useForm } from '@/hooks'
import ClassroomCascader from '@/components/ProSelect/ClassroomCascader.vue'

const router = useRouter()
const getMonthRange = (date: string | Date) => {
  if (!date) {
    date = new Date()
  }
  const firstDay = dayjs(date).startOf('month').format('YYYY-MM-DD') // 获取当月第一天
  const lastDay = dayjs(date).endOf('month').format('YYYY-MM-DD') // 获取当月最后一天

  return [
    firstDay,
    lastDay,
  ]
}

const { form } = useForm<ClassScheduleApi.ClassroomShecduleQuery>({
  dateFlag: 'month',
  classroomId: undefined,
  campusId: undefined,
  startTime: getMonthRange(new Date())[0],
  endTime: getMonthRange(new Date())[1],
})

const weekTimeSlots = ref<string[]>([])
const events = ref<CalendarEvent[] | undefined>()
const rooms = ref<string[]>([])

function generateTimeArray(startTime, endTime, interval: number = 1) {
  const startHour = Number.parseInt(startTime.split(':')[0])
  const startMinute = Number.parseInt(startTime.split(':')[1])
  const endHour = Number.parseInt(endTime.split(':')[0])
  const endMinute = Number.parseInt(endTime.split(':')[1])

  const timeArray: string[] = []
  let currentHour = startHour
  let currentMinute = startMinute

  while (currentHour < endHour || (currentHour === endHour && currentMinute <= endMinute)) {
    timeArray.push(`${currentHour.toString().padStart(2, '0')}:${currentMinute.toString().padStart(2, '0')}`)
    currentMinute += interval * 60
    while (currentMinute >= 60) {
      currentMinute -= 60
      currentHour++
    }
  }

  return timeArray
}

const setEvents = (data, type: string) => {
  const arr: CalendarEvent[] = []
  switch (type) {
    case 'month':
      for (const i in data) {
        arr.push({
          day: i,
          time: '',
          name: '',
          extra: data[i],
        })
      }
      events.value = arr
      break
    case 'week':
      for (const i in data) {
        for (const j in data[i]) {
          arr.push({
            day: j,
            time: i,
            name: '',
            extra: data[i][j],
          })
        }
      }
      events.value = arr
      break
    default:
      for (const i in data) {
        for (const j in data[i]) {
          arr.push({
            start: i.split('-')[0],
            end: i.split('-')[1],
            room: j,
            extra: data[i][j],
          })
        }
      }
      events.value = arr
  }
}
const loading = ref(false)
const getData = async () => {
  loading.value = true
  const res = await ClassScheduleApi.getClassroomShecdule(form)
  loading.value = false
  return res
}

const weekHandle = async () => {
  const res = await getData()
  if (res.weekMap) {
    weekTimeSlots.value = Object.keys(res.weekMap)
  }
  setEvents(res.weekMap, 'week')
}

const monthHandle = async () => {
  const res = await getData()
  if (res.monthMap) {
    setEvents(res.monthMap, 'month')
  }
}

const dayHandle = async () => {
  const res = await getData()
  if (res.dayMap) {
    const rm: string[] = []
    for (const i in res.dayMap) {
      rm.push(...Object.keys(res.dayMap[i]))
    }
    rooms.value = rm
    setEvents(res.dayMap, 'day')
  }
}

const modeChange = (e, value) => {
  events.value = []
  form.dateFlag = e
  if (e === 'day') {
    form.startTime = dayjs(value).format('YYYY-MM-DD')
    form.endTime = dayjs(value).format('YYYY-MM-DD')
    weekTimeSlots.value = generateTimeArray('08:00', '20:00')
    dayHandle()
  } else if (e === 'month') {
    form.startTime = getMonthRange(value)[0]
    form.endTime = getMonthRange(value)[1]
    monthHandle()
  } else {
    form.startTime = dayjs(value[0].date).format('YYYY-MM-DD')
    form.endTime = dayjs(value[value.length - 1].date).format('YYYY-MM-DD')
    weekHandle()
  }
}

const weekChange = async (val) => {
  form.startTime = dayjs(val[0].date).format('YYYY-MM-DD')
  form.endTime = dayjs(val[val.length - 1].date).format('YYYY-MM-DD')
  weekHandle()
}
const dayChange = (value) => {
  form.startTime = dayjs(value).format('YYYY-MM-DD')
  form.endTime = dayjs(value).format('YYYY-MM-DD')
  dayHandle()
}
const monthChange = (value) => {
  form.startTime = getMonthRange(value)[0]
  form.endTime = getMonthRange(value)[1]
  monthHandle()
}

onMounted(() => {
  monthHandle()
})

const toDetail = (data) => {
  router.push({ path: '/education/class/detail', query: { id: data.classId } })
}
</script>

<template>
  <ProPage title="" description="">
    <a-spin :loading="loading" style="width: 100%;height: 100%;">
      <Calendar
        :week-time-slots="weekTimeSlots"
        :day-rooms="rooms"
        :show-day-button="true"
        :events="events"
        :show-today="false"
        :gray-bg-title="true" :show-dot="false"
        :disabled="true"
        date-align="right"
        @mode-change="modeChange"
        @week-change="weekChange"
        @month-change="monthChange"
        @day-change="dayChange"
      >
        <template #title>
          <div>
            <a-space>
              <span>教室</span>
              <ClassroomCascader v-model:campus-id="form.campusId" v-model:classroom-id="form.classroomId" class="min-w-200px" />
            </a-space>
          </div>
        </template>
        <template #month-event="{ date, data }">
          <div class="month-event-item">
            <div class="font-size-[12px]">
              {{ date.getDate() }}
            </div>
            <div v-for="(item, index) in (data?.extra.slice(0, 2) || 0)" :key="index" class="ellipsis-1 event-name" @click="toDetail(item)">
              {{ item.className }}
            </div>
            <div v-if="data?.extra.length > 2" class="font-size-[14px] color-[#2d5cf6] font-600">
              +{{ data?.extra.length - 2 }}
            </div>
          </div>
        </template>
        <template #week-event="{ data }">
          <div class="month-event-item flex flex-col justify-center">
            <div v-for="(item, index) in (data?.extra.slice(0, 2) || 0)" :key="index" class="ellipsis-1 event-name" @click="toDetail(item)">
              {{ item.className }}
            </div>
            <div v-if="data?.extra.length > 2" class="font-size-[14px] color-[#2d5cf6] font-600">
              +{{ data?.extra.length - 2 }}
            </div>
          </div>
        </template>
        <template #day-event="{ data, range }">
          <div>
            <div class="font-size-[14px] color-[#1D2129]">
              {{ data?.extra[0].className }}
            </div>
            <div v-if="range >= 1" class="mt-2 flex items-center gap-1 font-size-[13px] color-[#666]">
              <icon-location size="15" style="color:#999" />
              <span>{{ data?.extra[0].leadTeacherName }}老师</span>
            </div>
            <div v-if="range >= 1" class="mt-2 flex items-center gap-1 font-size-[13px] color-[#666]">
              <icon-schedule size="14" style="color:#999" />
              <span>{{ data?.start }}-{{ data?.end }}</span>
            </div>
          </div>
        </template>
      </Calendar>
    </a-spin>
  </ProPage>
</template>

<style lang='less' scoped>
.month-event-item {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  text-align: left;
  background: #e8f3ff;
  padding: 6px;
  .event-name {
    position: relative;
    font-size: 12px;
    color: #1d2129;
    padding-left: 10px;
    margin: 4px 0;
    &:hover {
      color: rgb(var(--primary-6));
      cursor: pointer;
    }
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 6px;
      height: 6px;
      border-radius: 50%;
      background: #00b42a;
    }
  }
}
.ellipsis-1 {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
</style>
